﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using MinistryStandardPlatformWeb.Controllers.RealTime;
using MinistryStandardPlatformWeb.Models.ReportCenter;

namespace MinistryStandardPlatformWeb.Controllers.Reports
{
    [MenuAuthorized("42")]
    public class UnloadInRoadController : Controller
    {
        //
        // GET: /UnloadInRoad/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetData(string startTime, string endTime, List<string> sims)
        {
            if (!string.IsNullOrEmpty(startTime) && !string.IsNullOrEmpty(endTime) && sims != null && sims.Count != 0)
            {
                string sql = "select simid mSim,"
                + "cast(latitude as varchar(20)) mLat,"
                + "cast(longitude as varchar(20)) mLng,"
                + "unloadtype mType,"
                + "tofantime mStartTime,"
                + "tozhengtime mEndTime "
                + "from unload "
                + "where unloadtype='2' and inserttime >= '" + startTime + "' and inserttime <= '" + endTime + "' and ";
                for (int i = 0; i < sims.Count; i++)
                {
                    if (i == 0)
                    {
                        sql += "(";
                    }
                    sql += "simid='" + sims[i] + "' or ";
                    if (i == sims.Count - 1)
                    {
                        sql += "1=0) ";
                    }
                }
                string historyStr = RealTimeGet.getReportFromGeoBase(
                    CommonFunctions.GetLoginUser().UserId,
                    sql,
                    startTime,
                    endTime,
                    "0");
                List<UnloadStatistic> modelList = new List<UnloadStatistic>();
                if (historyStr != "error" && historyStr != "")
                {
                    try
                    {
                        modelList = CommonFunctions.JsonStrToObject<List<UnloadStatistic>>(historyStr);
                        MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
                        for (int i = 0; i < modelList.Count; i++)
                        {
                            UnloadStatistic model = modelList[i];
                            if (model.mType.Equals("0"))
                            {
                                model.mType = "区域内卸料";
                            }
                            else
                            {
                                model.mType = "区域外卸料";
                            }
                            if (i < 20)
                            {
                                model.mAddr = geoHelper.GgpsTranslate2BaiduPoi(model.mLng, model.mLat);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        return null;
                    }
                }
                else
                {
                }
                var json = new
                {
                    total = modelList.Count,
                    rows = (from r in modelList
                            select r).ToArray()
                };
                var serializer = new JavaScriptSerializer();
                serializer.MaxJsonLength = Int32.MaxValue;
                return Content(serializer.Serialize(json), "application/json");
            }
            return null;
        }

        /*解析地理位置*/
        [HttpPost]
        public ActionResult ParseAddr(string key, int page, List<string> lngs, List<string> lats)
        {//key为查询批次的唯一标示，防止前台点击“查询”重新查询另一批数据时，后台处理返回数据与前台数据不唯一
            if (lngs.Count == lats.Count)
            {
                MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();
                List<string> pois = new List<string>();
                for (int i = 0; i < lngs.Count; i++)
                {
                    if (lngs[i] == "" || lats[i] == "" || lngs[i] == "null" || lats[i] == "null")
                    {
                        pois.Add("");
                    }
                    else
                    {
                        pois.Add(geoHelper.GgpsTranslate2BaiduPoi(lngs[i], lats[i]));
                    }
                }
                var json = new
                {
                    key = key,
                    page = page,
                    pois = (from r in pois
                            select r).ToArray()
                };
                return Json(json);
            }
            return null;
        }


        [HttpPost]
        [MenuAuthorized("1", Order = 1)]
        public ActionResult ExportExcel()
        {
            List<UnloadStatistic> list = CommonFunctions.JsonStrToObject<List<UnloadStatistic>>(Request.Form["data"]);
            var sbHtml = new System.Text.StringBuilder();
            sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
            sbHtml.Append("<tr>");
            var lstTitle = new List<string> { "序号", "车牌号", "SIM卡号", "单位名称", "开始时间", "结束时间","卸料地点" };
            foreach (var item in lstTitle)
            {
                sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
            }
            sbHtml.Append("</tr>");

            for (int i = 0; i < list.Count; i++)
            {
                sbHtml.Append("<tr>");
                sbHtml.AppendFormat("<td>{0}</td>", i + 1);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mName);
                sbHtml.AppendFormat("<td style='vnd.ms-excel.numberformat:@;'>{0}</td>", list[i].mSim);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mDepart);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mStartTime);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mEndTime);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mAddr);
                sbHtml.Append("</tr>");
            }
            sbHtml.Append("</table>");

            //第一种:使用FileContentResult
            byte[] fileContents = System.Text.Encoding.Default.GetBytes(sbHtml.ToString());
            return File(fileContents, "application/ms-excel", "在途卸料.xls");

            ////第二种:使用FileStreamResult
            //var fileStream = new MemoryStream(fileContents);
            //return File(fileStream, "application/ms-excel", "fileStream.xls");

            ////第三种:使用FilePathResult
            ////服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.
            //var fileName = Server.MapPath("~/Files/fileName.xls");
            //return File(fileName, "application/ms-excel", "fileName.xls");
            //return null;
        }
    }
}
